package com.open.chat.server.utils;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
@Component
public class Https{
	private static Logger logger = LoggerFactory.getLogger(Https.class);
	@Autowired
	RestTemplate restTemplate;
    /**
     * post
     * @param url 请求地址
     * @param param 参数
     * @param returnClass 返回类型
     * @param status true:普通       false:json
     * @return
     */
    private <T> T post(String url, JSONObject js, Class<T> returnClass,boolean status) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(status?MediaType.APPLICATION_FORM_URLENCODED:MediaType.APPLICATION_JSON);
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        
        
        T t = null;
        if(status) {
        	//规定只能是对象
            if(js != null && js instanceof JSONObject) {
            	Iterator<Entry<String, Object>> iterator = js.entrySet().iterator();
            	while(iterator.hasNext()) {
            		Map.Entry<String, Object> entry = (Entry<String, Object>)iterator.next();
            		params.add(entry.getKey(), entry.getValue());
            	}
            	//params = JSONObject.parseObject(js.toJSONString(), new TypeReference<MultiValueMap<String, String>>(){});
            }
        	HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(params,headers);
        	t = restTemplate.postForObject(url, entity, returnClass);
        }else {
        	
        	HttpEntity<String> entity = new HttpEntity<>(js.toJSONString(),headers);
        	
        	t  = restTemplate.postForObject(url, entity, returnClass);
        	//System.out.println(JSON.toJSONString(a));
        }
        return t;
    }

    /**
     * post
     * @param url
     * @param params
     * @param returnClass
     * @return
     */
    public  <T> T post(String url, JSONObject params,Class<T> returnClass) {
       return post(url, params, returnClass,true);
    }
    /**
     * postJson
     * @param url
     * @param params  参数会被解析成json体
     * @param returnClass
     * @return
     */
    public  <T> T postJson(String url, JSONObject params,Class<T> returnClass) {
    	return post(url, params, returnClass,false);
    }
    
	
}